package cn.com.asd.file.controller;

import cn.com.asd.file.util.FastDFSClient;
import cn.com.asd.file.util.FastDFSFile;
import cn.netshop.pojo.Result;
import cn.netshop.pojo.StatusCode;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/file")
public class fileController {

    @PostMapping("/upload")
    public Result uploadFile(MultipartFile file){
        try{
            if(file == null){
                throw new RuntimeException("文件不存在");
            }

            String filename = file.getOriginalFilename();
            if(StringUtils.isEmpty(filename)){
                throw new RuntimeException("文件不存在");
            }

            String extName = filename.substring(filename.lastIndexOf(".") + 1);

            byte[] content = file.getBytes();

            FastDFSFile fastDFSFile = new FastDFSFile(filename,content,extName);

            String[] uploadResult = FastDFSClient.upload(fastDFSFile);
            String url = FastDFSClient.getTrackerUrl()+ uploadResult[0]+"/" + uploadResult[1];
            System.out.println(url);
            return new Result(true,StatusCode.OK,"上传成功",url);

        }catch (Exception e){
            e.printStackTrace();
        }

        return new Result(false, StatusCode.ERROR,"文件上传失败");
    }
}
